﻿using System;
using System.Collections.Generic;
using System.Text;
using Pixysoft.Framework.Configurations.Core;

namespace Pixysoft.Framework.Configurations.Controller
{
    class XmlUpdateController
    {
        public static void Update(IXmlNode nodeFrom, IXmlNode nodeTo)
        {
            //更新节点内容

            if (!string.IsNullOrEmpty(nodeFrom.Text))
                nodeTo.Text = nodeFrom.Text;


            //更新节点属性

            foreach (IXmlProperty property in nodeFrom.Properties)
            {
                if (nodeTo.Properties.Contains(property.Key))
                    nodeTo.Properties[property.Key] = property.Value;
                else
                    nodeTo.Properties.Add(property.Key, property.Value);
            }



            //更新节点子节点 双方按照顺序更新

            int nodeToIndex = 0;

            for (int i = 0; i < nodeFrom.Node.Count; i++)
            {
                IXmlNode childNodeFrom = nodeFrom.Node[i];

                IXmlNode childNodeTo;

                //寻找elementname一样的节点 如果没有 就返回

                while (true)
                {
                    if (nodeToIndex > nodeTo.Node.Count - 1)
                    {
                        childNodeTo = null;

                        nodeToIndex = i + 1;

                        break;
                    }

                    childNodeTo = nodeTo.Node[nodeToIndex++];

                    if (childNodeTo.ElementName.Equals(childNodeFrom.ElementName, StringComparison.OrdinalIgnoreCase))
                        break;
                }

                if (childNodeTo != null)
                {
                    Update(childNodeFrom, childNodeTo);
                }
                else
                {
                    IXmlNode newXmlToNode = new XmlNode(childNodeFrom.ElementName);

                    nodeTo.Nodes.Add(newXmlToNode);

                    Update(childNodeFrom, newXmlToNode);
                }
            }
        }
    }
}
